import pytest
import allure
import logging
from interface.interface import RequestsUtils
from utils.yaml_utils import read_yaml_all
from utils.read_ini import write_conf, clear_section_values
from utils.send_email import EmailManage


# 定义登录的配置
@pytest.fixture(scope='session')
def api():
    return RequestsUtils()


# # 会话开启，自动执行，，只要有新的会，就斗湖自动的执行这个登录， 会话结束的时， 清除就行
# @pytest.fixture(scope='session', autouse=True)
# def login(request, api):
#     """
#     这是一个特殊的后置处理方式
#     :param request:
#     :param api:
#     :return:
#     """
#     # 后置
#     def clear_data_finalizer():
#         with allure.step("执行测试用例后置，删除记录的数据"):
#             clear_section_values("data")
#     request.addfinalizer(clear_data_finalizer)
#
#     with allure.step("1.发送登录请求"):
#         # 前置
#         dict_data = read_yaml_all("usermanagement/management.yaml")[0]
#         res = api.requests_utils(**dict_data["login"])
#     with allure.step("2.登录成功后，将token值写入文件中"):
#         write_conf("data", "token", api.get_text(res.json(), "token"))


# 全局字典，用于统计测试结果
test_results = {
    'passed': 0,
    'failed': 0,
    'skipped': 0
}


def pytest_runtest_logreport(report):
    # 检查所有阶段的报告
    if report.when == 'setup' and report.skipped:
        test_results['skipped'] += 1
    elif report.when == 'call':
        if report.passed:
            test_results['passed'] += 1
        elif report.failed:
            test_results['failed'] += 1


def pytest_sessionfinish(session, exitstatus):
    # 在所有测试运行完成后输出结果统计
    logging.info("测试结果统计：")
    test_results_total = int(test_results['passed']) + int(test_results['failed']) + int(test_results['skipped'])
    pass_rate = (test_results['passed'] / test_results_total * 100 if test_results_total > 0 else 0)
    logging.info(f"总测试用例: {test_results_total}")
    logging.info(f"通过数量: {test_results['passed']}")
    logging.info(f"失败数量: {test_results['failed']}")
    logging.info(f"跳过数量: {test_results['skipped']}")
    logging.info(f"测试通过率: {pass_rate:.2f}%")

    logging.info("================所有测试结束================")
    logging.info("开始发送邮件........")
    # EmailManage().send_email(test_results_total, test_results, pass_rate)
    logging.info("邮件发送完成！")
